import os
import sys

#Our custom check; does libwaitzar work?
def CheckLibWaitzarWorks(context):
    #Inform the user
    context.Message('Running libwaitzar test cases...\n')
    
    #Link to libwaitar and run our tests
    result = True
    try:
        #Import the library
        from libwaitzar import WordBuilder, encoding, StringVec

        #Build the object
        modelpath = "/usr/share/waitzar/model2/Myanmar.model"
        mywordspath = StringVec()
        mywordspath.append("/usr/share/waitzar/model2/mywords.txt")
        localmw = os.path.join(os.path.join(os.path.expanduser("~"),".wz"), "mywords.txt")
        if os.path.isfile(localmw):
            mywordspath.append(localmw)
        model = WordBuilder(modelpath, mywordspath)
        
        #Test the return value for "kote"
        model.reset(True)
        model.typeLetter('k')
        model.typeLetter('o')
        model.typeLetter('t')
        model.typeLetter('e')

        #Test all key values: unicode, zawgyi, ascii
        tests = {encoding.unicode     : [u'\u1000\u102F\u1000\u103A', u'\u1000\u102F\u100B\u103A', u'\u1000\u102F\u1010\u103A', u'\u1000\u102F\u1015\u103A', u'\u1000\u102F\u1017\u103A'],
                              encoding.zawgyi       : [u'\u1000\u102F\u1000\u1039', u'\u1000\u102F\u100B\u1039', u'\u1000\u102F\u1010\u1039', u'\u1000\u102F\u1015\u1039', u'\u1000\u102F\u1017\u1039'], 
                              encoding.wininnwa   : [u'ukuf', u'uk#f', u'ukwf', u'ukyf', u'ukAf']}
        for enc,res in tests.iteritems():
            possibleWords = map(lambda x:model.getWordKeyStrokes(x, enc), model.getPossibleWords())
            if (possibleWords != res):
                context.Message('ERROR: WaitZar output failed for encoding: ' + str(enc) + '\n')
                context.Message('    ' + str(possibleWords) + '\n')
                context.Message('    ' + str(res) + '\n')
                result = False

        #There should be more test cases here, such as "shortcuts", output encodings, and other things
        # No need to go too far overboard, but we should at least ensure that python is linking ttro ctypes properly
    except:
        import traceback
        traceback.print_exc()
        result = False
    
    #Done
    context.Result(result)
    return result
    
    
#Our custom check; do basic engine tasks work?
def CheckEngineWorks(context):
    #Inform the user
    context.Message('Running ibus-waitzar engine checks...\n')
    
    #Load the engine, run our tests
    result = True
    try:
        #Import the libraries
        from libwaitzar import WordBuilder, encoding, StringVec
        sys.path.append('engine')
        import engine
        import ibus

        #Load a temporary engine, test it out
        from getpass import getuser
        if (getuser() == 'root'):
            context.Message('Skipping engine test (fails for root user)\n')
        else:
            myengine = engine.Engine(ibus.Bus(), '/com/redhat/IBus/engines/WaitZar/Engine/2')
            myengine.reset()
            myengine.testUpdate()
            myengine.reset()
            myengine.testUpdate()
    except:
        import traceback
        traceback.print_exc()
        result = False
    
    #Done
    context.Result(result)
    return result    
    
    
    

# Import the path from the user's environment
env = Environment(ENV = {'PATH' : os.environ['PATH']})

# Manage pkgconfig
env.ParseConfig('pkg-config --cflags --libs waitzar')

# Checks
if not env.GetOption('clean'):
    conf = Configure(env, custom_tests = {'CheckLibWaitzarWorks' : CheckLibWaitzarWorks, 'CheckEngineWorks' : CheckEngineWorks})

    # Check for the existence of libwaitzar
    if not conf.CheckLibWaitzarWorks():
        print 'ERROR: libwaitzar test cases failed'
        Exit(1)

    #General engine check
    if not conf.CheckEngineWorks():
        print 'ERROR: ibus-waitzar engine test failed'
        Exit(1)

    env = conf.Finish()



#NOTE: The following files are probably installed in 
#   /usr/local/lib/
#      libwaitzar.a
#      libwaitzar.la
#      libwaitzar.so
#      libwaitzar.so.1
#      libwaitzar.so.1.0.0
#NOTE: Normal library (libwaitzar1) installs:
#         usr/lib/libwaitzar.so.1
#         usr/lib/libwaitzar.so.1.0.0
#      Libwaitzar-dev installs:
#         usr/include/*
#         usr/lib/libwaitzar.so
#         usr/lib/libwaitzar.la
#         usr/lib/pkgconfig/waitzar.pc
#
#Expect the model data to be stored in:
#   /usr/local/share/waitzar/model2
#      Myanmar.model
#      mywords.txt
#
#Header files in:
#   /usr/local/include/waitzar
#      fontconv.h
#      fontmap.h
#      lib.h
#      SentenceList.h
#      regex.h
#      WordBuilder.h
#
#Pkgconfig data in:
#   /usr/local/lib/pkgconfig/
#      waitzar.pc


#Install the engine in its appropriate location
env.Install('/usr/share/ibus-waitzar/engine', 'engine/engine.py')
env.Install('/usr/share/ibus-waitzar/engine', 'engine/factory.py')
env.Install('/usr/share/ibus-waitzar/engine', 'engine/main.py')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/wz.svg')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/input_uni.svg')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/input_wi.svg')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/input_zg.svg')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/num_eng.svg')
env.Install('/usr/share/ibus-waitzar/icons', 'icons/num_mm.svg')
env.Install('/usr/share/ibus-waitzar/setup', 'setup/main.py')

env.Install('/usr/lib/ibus-waitzar', 'ibus-engine-waitzar')
env.Install('/usr/lib/ibus-waitzar', 'ibus-setup-waitzar')

env.Install('/usr/share/ibus/component', 'waitzar.xml')

#Convenience target
env.Alias('install', Split('/usr/share/ibus-waitzar /usr/lib/ibus-waitzar /usr/share/ibus/component'))




